package com.youfang.sixthmedia.ui;

import java.util.Date;
import java.util.List;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;

import com.gzit.common.async.AsynCallback;
import com.gzit.common.async.LoadingCallback;
import com.gzit.utils.AndroidUtils;
import com.gzit.utils.DateUtil;
import com.youfang.sixthmedia.LoginActivity;
import com.youfang.sixthmedia.R;
import com.youfang.sixthmedia.YouFangApplication;
import com.youfang.sixthmedia.common.BaiduMapActivity;
import com.youfang.sixthmedia.common.BuildingAdapter;
import com.youfang.sixthmedia.common.YoufangContext;
import com.youfang.sixthmedia.controller.AdController;
import com.youfang.sixthmedia.controller.LogoController;
import com.youfang.sixthmedia.message.GethousesRequest;
import com.youfang.sixthmedia.message.GethousesResponse;
import com.youfang.sixthmedia.message.model.Advertisment;
import com.youfang.sixthmedia.message.model.Building;
import com.youfang.sixthmedia.net.Net;
import com.youfang.sixthmedia.net.Response;
import com.youfang.sixthmedia.ui.detail.TabDetailBuildingActivity;
import com.youfang.sixthmedia.widget.AdImageSwitcher;
import com.youfang.sixthmedia.widget.GZITPullToRefreshListView;
import com.youfang.sixthmedia.widget.GZITPullToRefreshListView.OnBottomListener;
import com.youfang.sixthmedia.widget.GZITPullToRefreshListView.OnRefreshListener;

//new building ,groupon building ,discount building are all derived from this base class
public abstract class BaseBuildingActivity extends BaiduMapActivity {

	protected GZITPullToRefreshListView listview;
	protected BuildingAdapter adapter;
	protected int page = 1;

	protected LogoController logoController = new LogoController();

	protected AdImageSwitcher adImageSwitcher;

	// child activity should override this method
	// to provide the types of house like discount or group on...
	protected abstract GethousesRequest makeRequest();

	protected boolean shouldLoginToMakeRequest() {
		return false;
	}

	protected GethousesResponse markeResponse() {
		return new GethousesResponse();
	}

	@Override
	protected void onCreate(Bundle arg0) {
		initUI();
		super.onCreate(arg0);
	}

	public void initUI() {

		this.listview = (GZITPullToRefreshListView) this
				.findViewById(R.id.listview);
		this.adapter = new BuildingAdapter(this);
		this.listview.setAdapter(adapter);
		this.logoController.setup(listview, adapter);
		this.listview.setOnRefreshListener(new OnRefreshListener() {

			@Override
			public void onRefresh() {
				remoteRefresh();
			}
		});
		this.listview.setOnBottomListener(new OnBottomListener() {

			@Override
			public void onBottomClick() {
				remoteMore();
			}

			@Override
			public void onBottom() {

			}
		});

		// 切换列表和地图视图
		View switcher = this.findViewById(R.id.switch_container_rg);
		if (switcher != null) {
			((RadioGroup) switcher)
					.setOnCheckedChangeListener(new OnCheckedChangeListener() {

						@Override
						public void onCheckedChanged(RadioGroup group,
								int checkedId) {
							switch (checkedId) {
							case R.id.listRB:
								findViewById(R.id.list_container)
										.setVisibility(View.VISIBLE);
								findViewById(R.id.map_container).setVisibility(
										View.INVISIBLE);
								break;
							case R.id.mapRB:
								findViewById(R.id.map_container).setVisibility(
										View.VISIBLE);
								findViewById(R.id.list_container)
										.setVisibility(View.INVISIBLE);

								// 属性地图
								refreshMapview();

								break;
							}

						}
					});
		}

		this.listview.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {

				// 点中楼房记录
				if (id > 0) {
					gotoDetailActivity("" + id);
					return;
				}

				// TD:点中广告...

			}
		});

		// 执行刷新动作, 加载楼盘数据
		this.listview.refresh();

		// 做一些广告的事宜
		doAdStuff();

	}

	private BroadcastReceiver adReceiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {

			// 有新广告到来，重新加载广告...
			loadLocalAD();
		}
	};

	private void doAdStuff() {
		adImageSwitcher = (AdImageSwitcher) this
				.findViewById(R.id.adImageSwitcher);
		listview.showAdLoading();
		loadLocalAD();

	}

	private void loadLocalAD() {

		new AsyncTask<String, Integer, List<Advertisment>>() {

			@Override
			protected List<Advertisment> doInBackground(String... params) {

				return ((YouFangApplication) getApplication()).adController
						.localAD();

			}

			protected void onPostExecute(List<Advertisment> ads) {

				if (ads != null && !ads.isEmpty()) {

					// 关闭loading并显示出广告
					listview.hideAdLoading();

					// 切换广告
					adImageSwitcher.setAds(ads);
				}

			};

		}.execute("");

	}

	// //////////////////////

	public void refreshMapview() {
		List<Building> building = this.adapter.getmObjects();
		this.mapview.getOverlays().clear();
		if (!building.isEmpty()) {
			this.mapview.getOverlays().add(new BuildingOverlay(this, building));
			this.fitPoints(building);

		}
		this.mapview.invalidate();
	}

	public void gotoDetailActivity(String id) {
		Intent intent = new Intent();
		intent.setClass(this, TabDetailBuildingActivity.class);
		intent.putExtra("id", id);
		this.startActivity(intent);

	}

	public void remoteMore() {

		if (this.shouldLoginToMakeRequest()) {
			if (!YoufangContext.isLogined()) {
				listview.onBottomFinish();
				gotoLoginActivity();
				return;

			}
		}

		GethousesRequest req = makeRequest();
		req.setCityid(YoufangContext.getCity().cityid);
		req.setPage(page);

		Net.doHttpRemote(this, req, markeResponse(),
				new AsynCallback<Response>() {

					@Override
					public void onFinish(Response r) {
						super.onFinish(r);
						listview.onBottomFinish();
					}

					@Override
					public void callback(Response r) {
						if (!r.isOk()) {
							return;
						}

						GethousesResponse resp = (GethousesResponse) r;
						List<Building> buildings = resp.getBuildings();
						adapter.addAll(buildings);

						// logo控制器
						logoController.onMore(buildings);

						// 页码递增
						page++;

					}
				}, LoadingCallback.EMPTY);

	}

	public void remoteRefresh() {

		if (this.shouldLoginToMakeRequest()) {
			if (!YoufangContext.isLogined()) {
				listview.onRefreshComplete();
				gotoLoginActivity();
				return;

			}
		}

		// 重置页码
		page = 1;
		GethousesRequest req = makeRequest();
		req.setCityid(YoufangContext.getCity().cityid);
		req.setPage(page);
		Net.doHttpRemote(this, req, markeResponse(),
				new AsynCallback<Response>() {

					@Override
					public void onFinish(Response r) {
						super.onFinish(r);
						listview.onRefreshComplete();
					}

					@Override
					public void callback(Response r) {
						if (!r.isOk()) {
							return;
						}

						GethousesResponse resp = (GethousesResponse) r;
						List<Building> buildings = resp.getBuildings();
						adapter.reload(buildings);
						listview.setLastUpdated(DateUtil
								.dateTime2String(new Date()));
						listview.setSelection(1);

						// 控制楼房图标
						logoController.onRefresh(buildings);

						// 页码递增
						page++;

						if (buildings.isEmpty()) {
							AndroidUtils.toastShort("当前条件下没有加载到楼盘数据");

						}

					}
				}, LoadingCallback.EMPTY);

	}

	private void gotoLoginActivity() {

		Intent intent = new Intent();
		intent.setClass(this, LoginActivity.class);
		this.startActivityForResult(intent, LOGIN_REQUEST_CODE);

	}

	private static final int LOGIN_REQUEST_CODE = 1;

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);

		if (resultCode != Activity.RESULT_OK) {
			return;
		}

		switch (requestCode) {
		case LOGIN_REQUEST_CODE:
			if (resultCode == Activity.RESULT_OK) {
				this.listview.refresh();
			}
			break;
		}
	}

	@Override
	protected void onResume() {
		super.onResume();

		// 注册新广告通知接收器
		IntentFilter filter = new IntentFilter();
		filter.addAction(AdController.AD_ACTION);
		registerReceiver(adReceiver, filter);
	}

	@Override
	protected void onPause() {
		super.onPause();
		unregisterReceiver(adReceiver);
	}

	@Override
	protected void onStop() {
		super.onStop();
		logoController.onStop();
	}

}
